import backtrader as bt
import datetime

# --- 步骤 1: 创建 oracle.csv 文件 ---
# 将CSV数据定义为一个多行字符串
csv_data = """Date,Open,High,Low,Close,Adj Close,Volume
2000-01-03,28.34375,28.5,26.0625,26.375,22.864731,162226400
2000-01-04,25.75,26.625,24.75,25.078125,21.74052,103362400
2000-01-05,24.3125,26.25,23.5,23.8125,20.64332,133233600
2000-01-06,23.5,24.6875,22.875,23.0,19.939102,93294400
2000-01-07,22.9375,24.0,22.625,23.875,20.701817,75827200
2000-01-10,24.125,25.4375,23.8125,25.3125,21.947231,79174400
2000-01-11,24.875,25.5,24.3125,24.8125,21.5105,68142400
2000-01-12,24.5,24.75,23.8125,24.0625,20.86438,57576800
2000-01-13,24.3125,24.5,23.375,23.8125,20.64332,59695200
2000-01-14,24.0,24.4375,23.625,24.21875,20.999687,46536000
2000-01-18,24.5,25.875,24.25,25.5,22.109594,66912000
2000-01-19,25.25,26.5,25.0,25.8125,22.38048,68326400
2000-01-20,26.0,26.0625,25.125,25.25,21.892691,62348800
2000-01-21,25.5,25.6875,24.375,24.5,21.240211,57450400
2000-01-24,24.875,25.125,23.875,24.0,20.809982,50482400
2000-01-25,23.875,24.8125,23.75,24.625,21.35712,50360800
2000-01-26,24.3125,24.75,23.3125,23.625,20.48082,41012000
2000-01-27,23.5625,24.25,23.0625,23.3125,20.210081,42464000
2000-01-28,23.125,23.6875,22.5,22.75,19.722235,46882400
2000-01-31,22.625,23.625,22.0625,23.5,20.372574,67832800
"""

# 使用 'w' 模式打开文件（如果文件不存在则创建），并将数据写入
with open('oracle.csv', 'w') as f:
    f.write(csv_data)

print("'oracle.csv' file created successfully.")
print("-" * 30)

# --- 步骤 2: 运行 Backtrader 程序 (和之前的代码一样) ---

# 创建 Strategy 子类
class MyFirstStrategy(bt.Strategy):
    def next(self):
        # 简单打印日期和收盘价
        print(f'{self.datas[0].datetime.date(0)} --- Close: {self.datas[0].close[0]}')

# 实例化 Cerebro 引擎
cerebro = bt.Cerebro()

# 加载我们刚刚创建的数据文件
data = bt.feeds.YahooFinanceCSVData(
    dataname='oracle.csv',
    fromdate=datetime.datetime(2000, 1, 1),
    todate=datetime.datetime(2000, 1, 31)
)

# 将数据添加到 Cerebro
cerebro.adddata(data)

# 将策略添加到 Cerebro
cerebro.addstrategy(MyFirstStrategy)

# 设置初始资金
cerebro.broker.setcash(100000.0)
print(f'Starting Portfolio Value: {cerebro.broker.getvalue():.2f}')

# 运行 cerebro.run()
cerebro.run()

# 打印最终结果
print(f'Final Portfolio Value: {cerebro.broker.getvalue():.2f}')

# (可选) 绘制结果
# cerebro.plot()